package net.jcip.examples.chapter3;

public class ThisEscapeExample {
    final  int a;
    int b=0;
    static ThisEscapeExample obj;
    public ThisEscapeExample(){
        a=1;
        b=1;
        obj=this;
    }
    public static void main(String[] args) {
        /**
         * 线程A：模拟构造器中this逃逸,将未构造完全对象引用抛出
         */
        Thread threadA =new Thread(() -> obj=new ThisEscapeExample());



        /**
         * 线程B：读取对象引用，访问a/b变量
         */
        Thread threadB=new Thread(() -> {
            ThisEscapeExample objA = obj;
            try {
                System.out.println(objA.b);
            }catch (NullPointerException e){
                System.out.println("发生空指针错误：普通变量b未被初始化");
            }
            try {
                System.out.println(objA.a);
            } catch (NullPointerException e) {
                System.out.println("发生空指针错误：final变量a未被初始化");
            }
        });
        threadB.start();
    }
}